import './login.scss'
import { Button, Form, Input, message, Tooltip } from 'antd'
import { UserOutlined, LockOutlined } from '@ant-design/icons'
import LogoIcon from '../../assets/logo.png'
import React, { useEffect } from 'react'
import { login } from '../../api/login'
import { useDispatch } from 'react-redux'
import { setToken } from '../../store/userSlice'
import { useNavigate } from 'react-router-dom'
// 引入保存 navigate 的对象
import { navigatorRef } from '../../utils/navigatorRef'

// 自定义密码组件
// 因为 密码表单里面 添加了 tooltip 组件, 表单无法直接校验 password, 所以需要进行封装, 然后再再表单中使用
const CustPassword: React.FC<any> = (props: any) => {
  // onChange 事件是父组件自动传过来的
  const { handleLogin, passWordKeyDown, showPTip, onChange } = props
  const [passwordVal, setPasswordVal] = React.useState('')

  const changePassword = (e: React.ChangeEvent<HTMLInputElement>) => {
    setPasswordVal(e.target.value)
    onChange?.(e.target.value)
  }
  return (
    <Tooltip placement="right" open={showPTip} title={'当前是大写'}>
      <Input.Password
        prefix={<LockOutlined />}
        placeholder="密码"
        size="small"
        onPressEnter={handleLogin}
        onKeyUp={passWordKeyDown}
        value={passwordVal}
        onChange={changePassword}
      />
    </Tooltip>
  )
}
function Login() {
  const [formInstance] = Form.useForm()
  const [messageApi, contextHolder] = message.useMessage()
  const [showTip, setShowTip] = React.useState<boolean>(false)
  const dispatch = useDispatch()

  const navigate = useNavigate()
  // 将 useNavigate 赋值给 navigatorRef.navigate, 以便在非组件中使用导航
  useEffect(() => {
    navigatorRef.navigate = navigate
  }, [navigate])

  const handleLogin = () => {
    formInstance
      .validateFields()
      .then((formData) => {
        login(formData)
          .then((res: any) => {
            dispatch(setToken(res))
          })
          .catch(() => {
            messageApi.open({
              type: 'error',
              content: '当前账号无权限登录'
            })
          })
      })
      .catch((err) => {
        messageApi.open({
          type: 'error',
          content: '请输入账号和密码'
        })
      })
  }

  const passWordKeyDown = (e: any) => {
    setShowTip(false)
    if (showTip) {
      return
    }
    let timer: any
    if (e.getModifierState('CapsLock')) {
      // 监听是否按下 'CapsLock' 键
      setShowTip(true)
      timer = setTimeout(() => {
        setShowTip(false)
      }, 3000)
    } else {
      clearTimeout(timer)
      setShowTip(false)
    }
  }
  return (
    <div className="login-bg">
      <div className="login-card">
        <div className="login-form">
          <div className="login-logo">
            <img src={LogoIcon} alt="动力港口" />
          </div>
          <Form
            form={formInstance}
            name="base"
            className="form-base"
            labelCol={{ span: 0 }}
            wrapperCol={{ span: 24 }}
            autoComplete="off"
            scrollToFirstError={true}
          >
            <Form.Item
              label={null}
              name="username"
              rules={[{ required: true, message: '请输入账号' }]}
            >
              <Input
                prefix={<UserOutlined />}
                placeholder="账号"
                size="small"
                onPressEnter={handleLogin}
              />
            </Form.Item>

            <Form.Item
              label={null}
              name="password"
              rules={[{ required: true, message: '请输入密码' }]}
            >
              <CustPassword
                handleLogin={handleLogin}
                passWordKeyDown={passWordKeyDown}
                showPTip={showTip}
              />
            </Form.Item>

            <Form.Item label={null}>
              <Button
                type="primary"
                size="small"
                style={{ width: '100%' }}
                onClick={handleLogin}
              >
                {contextHolder}
                登录
              </Button>
            </Form.Item>
          </Form>
        </div>
      </div>
    </div>
  )
}

export default Login
